﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using TGM.Properties;

namespace TGM
{
    public class Engine
    {
        private readonly CookieContainer cookieContainer = new CookieContainer();

        public Engine()
        {
            ServicePointManager.ServerCertificateValidationCallback =
                (RemoteCertificateValidationCallback) Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback));
        }

        public string FamilyName { get; set; }

        public ItemConfig ItemConfig { get; set; }

        public MainForm Owner { get; set; }

        public string Pass { get; set; }

        public string RegCode { get; set; }

        public string User { get; set; }

        public void Execute()
        {
            string url = Step1();
            RegCode = Step2(url);
            Step3();
            Step4();
            Step5();
        }

        public Image ReadImageFromResponse(HttpWebResponse response)
        {
            Stream responseStream = response.GetResponseStream();
            Image image = Image.FromStream(responseStream);
            responseStream.Close();
            response.Close();
            return image;
        }

        public string ReadStringFromResponse(HttpWebResponse response, Encoding encoding)
        {
            var reader = new StreamReader(response.GetResponseStream(), encoding);
            string str = reader.ReadToEnd();
            reader.Close();
            response.Close();
            return str;
        }

        public bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public string Step1()
        {
            var request = (HttpWebRequest) WebRequest.Create(Settings.Default.LoginUrl);
            request.CookieContainer = cookieContainer;
            var response = (HttpWebResponse) request.GetResponse();
            string str = ReadStringFromResponse(response, Encoding.GetEncoding("GB2312"));
            int index = str.IndexOf("/register/checkregcode.html?");
            int num2 = str.IndexOf("\"", index);
            return ("https://login.passport.the9.com/" + str.Substring(index, num2 - index));
        }

        private string Step2(string url)
        {
            var request = (HttpWebRequest) WebRequest.Create(url);
            request.CookieContainer = cookieContainer;
            var response = (HttpWebResponse) request.GetResponse();
            Image image = ReadImageFromResponse(response);
            Owner.SetRegImge(image);
            var form = new RegForm();
            form.ShowDialog(Owner);
            return form.RegCode;
        }

        private void Step3()
        {
            var request = (HttpWebRequest) WebRequest.Create("https://passport.the9.com/index/login/dologin.html");
            request.CookieContainer = cookieContainer;
            request.Method = "POST";
            request.Headers.Add("X-Requested-With", "XMLHttpRequest");
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Accept = "application/json, text/javascript, */*";
            request.Referer = Settings.Default.LoginUrl;
            string s = string.Format("siteid=9000&redurl=http%253a%252f%252fitem.ge.the9.com%252fLogin.aspx%253ffrom%253d%25252fDefault.aspx&loginname={0}&password={1}&regcode={2}", User, Pass, RegCode);
            byte[] bytes = Encoding.ASCII.GetBytes(s);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, s.Length);
            requestStream.Close();
            var response = (HttpWebResponse) request.GetResponse();
            string str2 = ReadStringFromResponse(response, Encoding.GetEncoding("GB2312"));
        }

        private void Step4()
        {
            var request = (HttpWebRequest) WebRequest.Create("http://item.ge.the9.com/Default.aspx");
            request.CookieContainer = cookieContainer;
            var response = (HttpWebResponse) request.GetResponse();
            string str = ReadStringFromResponse(response, Encoding.GetEncoding("GB2312"));
            int index = str.IndexOf("name=info value='");
            int num2 = str.IndexOf("'", (index + 20));
            string str2 = str.Substring(index + 0x11, (num2 - index) - 0x11);
            index = str.IndexOf("name=sig value='");
            num2 = str.IndexOf("'", (index + 20));
            string str3 = str.Substring(index + 0x10, (num2 - index) - 0x10);
            request = (HttpWebRequest) WebRequest.Create("http://item.ge.the9.com/Login.aspx?from=%2fDefault.aspx");
            request.Method = "POST";
            request.CookieContainer = cookieContainer;
            request.ContentType = "application/x-www-form-urlencoded";
            string s = string.Format("info={0}&sig={1}", str2, str3);
            byte[] bytes = Encoding.ASCII.GetBytes(s);
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(bytes, 0, s.Length);
            requestStream.Close();
            response = (HttpWebResponse) request.GetResponse();
            str = ReadStringFromResponse(response, Encoding.UTF8);
        }

        public void Step5()
        {
            if (!string.IsNullOrEmpty(RegCode) && (ItemConfig != null))
            {
                var request = (HttpWebRequest) WebRequest.Create(" http://item.ge.the9.com/ajaxpro/GE.AwardWeb.Gateway,GE.AwardWeb.ashx");
                request.CookieContainer = cookieContainer;
                request.Method = "POST";
                request.KeepAlive = true;
                request.Expect = null;
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.126 Safari/533.4 ChromePlus/1.4.1.0";
                request.Headers.Add("X-AjaxPro-Method", "SendItems");
                request.Referer = "http://item.ge.the9.com/Default.aspx";
                request.ContentType = "\ttext/plain; charset=utf-8";
                request.AutomaticDecompression = DecompressionMethods.GZip;
                string s = "{\"itemInfo\":\"" + ItemConfig.GetItemString() + "\",\"siteId\":\"9001\",\"worldId\":\"1011\",\"familyName\":\"{" + FamilyName + "}\"}";
                byte[] bytes = Encoding.UTF8.GetBytes(s);
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                var response = (HttpWebResponse) request.GetResponse();
                string str2 = ReadStringFromResponse(response, Encoding.UTF8);
                Console.WriteLine(str2);
                Owner.OutputMsg(str2);
            }
        }
    }
}